﻿using System;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
using OTS.Utility;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using Extensions;

namespace OTS
{
    public partial class Odeme : XForm
    {
        Pen pen = new Pen(Brushes.Red, 2);
        Color color;
         
        DataTable dtTatil;
        DataTable dtOdeme;
        
         
        public Odeme()
        {
            InitializeComponent();
        }

        private void Odeme_Load(object sender, EventArgs e)
        { 
            RefreshData();

            gvMaster.RowCellStyle += gvMaster_RowCellStyle;
            gvMaster.CustomDrawCell += gvMaster_CustomDrawCell;
             
            gvMaster.FocusedColumnChanged += gvMaster_FocusedColumnChanged;
            gvMaster.FocusedRowChanged += gvMaster_FocusedRowChanged;
            
            btnGuncelle.Click += btnGuncelle_Click;
           
            colorPickEdit1.Color = Color.FromArgb(AppSession.UserInfo.ArkaplanRengi);
            colorPickEdit1.EditValueChanged += colorPickEdit1_EditValueChanged;
        }
         

        void btnGuncelle_Click(object sender, EventArgs e)
        {
            RefreshData();
        }
         
        private void gvMaster_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {
            if (e.Column.AbsoluteIndex == 0)
                e.Handled = false;
            else
            {
                if (e.CellValue != DBNull.Value)
                {
                    string filter = string.Format(CultureInfo.InvariantCulture, "Tarih = #{0}#", (DateTime)e.CellValue);
                    decimal capacity = dtOdeme.Compute("SUM(Tutar)", filter).ToDecimalNN();
                    //if (capacity > AppSession.MainForm.Limit)
                    //    capacity = AppSession.MainForm.Limit;

                    //e.Cache.DrawRectangle(pen, new Rectangle(e.Bounds.X, e.Bounds.Y + 32, ((int)(e.Bounds.Width * capacity / AppSession.MainForm.Limit)), 3));
                }
            }
        }


        void colorPickEdit1_EditValueChanged(object sender, EventArgs e)
        {
            color = colorPickEdit1.Color;
            AppSession.DataManager.ExecuteDataSet("UpdPref", AppSession.UserInfo.KullaniciId, "BackColor", color.ToArgb());
            gvMaster.RefreshData();
        }

        DateTime LastModifiedOn = new DateTime(2000, 1, 1);

        public override void RefreshData()
        {
            DataSet ds = AppSession.DataManager.ExecuteDataSet("GetData", 0, LastModifiedOn);

            gvMaster.Init(ds.Tables[0]);
            dtOdeme = ds.Tables[1];
            dtTatil = ds.Tables[2];
  
            if (dtOdeme.Rows.Count > 0)
            LastModifiedOn = (DateTime)dtOdeme.Compute("Max(Tarih)", "");
             
            gvMaster.Columns["Ay"].DisplayFormat.FormatType = FormatType.DateTime;
            gvMaster.Columns["Ay"].DisplayFormat.FormatString = "MMMM.yy";
            gvMaster.MakeReadOnly();
             
           
            System.Globalization.CultureInfo uiCulture = (System.Globalization.CultureInfo)Thread.CurrentThread.CurrentUICulture.Clone();
            uiCulture.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Monday;
            System.Threading.Thread.CurrentThread.CurrentUICulture = uiCulture;

            System.Globalization.CultureInfo culture = (System.Globalization.CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
            culture.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Monday;
            System.Threading.Thread.CurrentThread.CurrentCulture = culture;

            string[] wd = "Pzt.Sa.Çar.Per.Cu.Ct.Pz".Split(".".ToCharArray());
            for (int i = 1; i < 38; i++)
                gvMaster.Columns[i.ToString()].Caption = wd[(i + 5) % 7] + ".";

            gvMaster.RowHeight = 36;
            gvMaster.Appearance.Row.Font = new Font("Calibri", 16, FontStyle.Bold);

            gvMaster.OptionsView.ShowAutoFilterRow = false;
            gvMaster.BestFitColumns(); 

            for (int i = 1; i < 38; i++)
            {
                gvMaster.Columns[i].DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                gvMaster.Columns[i].DisplayFormat.FormatString = "dd";
            }

            gvMaster.BestFitColumns();
        }
         
        #region gvMaster_FocusedCellChanged
        void gvMaster_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            gvMaster_DoFocusedCellChanged();
        }

        void gvMaster_FocusedColumnChanged(object sender, FocusedColumnChangedEventArgs e)
        {
            gvMaster_DoFocusedCellChanged();
        }

        bool internalChanging = false;
        void gvMaster_DoFocusedCellChanged()
        {
            if (internalChanging)
                return;
            internalChanging = true;
            BeginInvoke(new MethodInvoker(delegate
            {
                gvMaster_FocusedCellChanged();
                internalChanging = false;
            }));
        }
        #endregion

        void gvMaster_FocusedCellChanged()
        {
            object oDate = gvMaster.GetFocusedValue();

            if (oDate != DBNull.Value)
            {
                DateTime date = (DateTime)oDate;
                string filter = string.Format(CultureInfo.InvariantCulture, "Gun = #{0}#", date);

                lblHeader.Text = date.ToShortDateString() + " - " + GetWeek(date).ToString() + ". hafta";

                string filterTotal = string.Format(CultureInfo.InvariantCulture, "Tarih = #{0}#", date);
                decimal capacityTotal = dtOdeme.Compute("SUM(Tutar)", filterTotal).ToDecimalNN();
                if (capacityTotal == -1)
                    capacityTotal++;

            }
            else
            {
                lblHeader.Text = string.Empty;
            }
        }

        void gvMaster_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle < 0)
                return;

            if (e.Column.FieldName == "Ay")
            {
                e.Appearance.BackColor = e.Appearance.BackColor2 = Color.DimGray;
                e.Appearance.ForeColor = Color.White;
            }
            else
            {
                e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);

                if (e.CellValue != DBNull.Value)
                {
                    DateTime date = (DateTime)e.CellValue;

                    if (TatilMi(date))
                        e.Appearance.BackColor = color;
                }
                else
                    e.Appearance.BackColor = e.Appearance.BackColor2 = Color.White;

                if (e.Column == gvMaster.FocusedColumn && e.RowHandle == gvMaster.FocusedRowHandle)
                    e.Appearance.BackColor = e.Appearance.BackColor2 = Color.YellowGreen;
            }
        }

        bool TatilMi(DateTime date)
        {
            string filter = string.Format(CultureInfo.InvariantCulture, "Tarih = #{0}#", date);
            if (dtTatil.Select(filter, string.Empty).Length > 0)
                return true;
            else
            {
                DayOfWeek DOW = date.DayOfWeek;
                if (DOW == DayOfWeek.Saturday || DOW == DayOfWeek.Sunday)
                    return true;
                else
                    return false;
            }
        }

        DateTime GetEfektifDate(DateTime start)
        {
            while (TatilMi(start))
                start = start.AddDays(1);

            return start;
        }

        int GetWeek(DateTime tarih)
        {
            CultureInfo myCI = new CultureInfo("en-US");
            Calendar myCal = myCI.Calendar;

            CalendarWeekRule myCWR = myCI.DateTimeFormat.CalendarWeekRule;
            DayOfWeek myFirstDOW = DayOfWeek.Monday;

            return myCal.GetWeekOfYear(tarih, myCWR, myFirstDOW);
        }

        
    }
}